﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using DidaManager.Log;
using RestSharp;
using RestSharp.Authenticators;
using RestSharp.Extensions;
using DidaManager.Native.Network;

namespace DidaManager.Native.RemoteTransmission
{
    namespace NSProduct
    {
        public class MyProduct
        {
            public string createTime { get; set; } = string.Empty;
            public string description { get; set; } = string.Empty;
            public string groupPortId { get; set; } = string.Empty;
            public string id { get; set; } = string.Empty;
            public string name { get; set; } = string.Empty;
            public int status { get; set; } = 0;
            public int type { get; set; } = 0;
            public string userId { get; set; } = string.Empty;

        }

        public class MyProductList
        {
            public string code { get; set; } = string.Empty;
            public string msg { get; set; } = string.Empty;
            public List<MyProduct> data { get; set; } = new List<MyProduct>();
        }
    }

    namespace NSDevice
    {
        public class MyDevice
        {
            public string clientId { get; set; } = string.Empty;
            public string createTime { get; set; } = string.Empty;
            public string description { get; set; } = string.Empty;
            public string id { get; set; } = string.Empty;
            public string isEnabled { get; set; } = string.Empty;
            public string lastConnectIp { get; set; } = string.Empty;
            public string lastConnectTime { get; set; } = string.Empty;
            public string name { get; set; } = string.Empty;
            public string productId { get; set; } = string.Empty;
            public int status { get; set; } = 0;//1 离线   2 在线   3 未激活


        }
        public partial class MyDeviceList
        {
            [JsonProperty("code")]
            public string Code { get; set; } = string.Empty;

            [JsonProperty("msg")]
            public string Msg { get; set; } = string.Empty;

            [JsonProperty("data")]
            public List<MyDevice> data { get; set; } = new List<MyDevice>();

        }

        public partial class Data
        {
            [JsonProperty("data")]
            public System.Collections.Generic.Dictionary<string, string>[] data { get; set; } = new System.Collections.Generic.Dictionary<string, string>[0];

            [JsonProperty("count")]
            public long Count { get; set; } = 0;
        }

        public class TransPortList
        {
            public class DevConfig
            {
                [JsonProperty("id")]
                public string Id { get; set; } = string.Empty;

                [JsonProperty("portConfigId")]
                public string PortConfigId { get; set; } = string.Empty;

                [JsonProperty("devName")]
                public string DevName { get; set; } = string.Empty;

                [JsonProperty("devAddr")]
                public int? DevAddr { get; set; } = 0;

                [JsonProperty("floatOrder")]
                public int FloatOrder { get; set; } = 0;
                // Add other properties as needed
            }

            public class PortConfig
            {
                [JsonProperty("id")]
                public string Id { get; set; } = string.Empty;

                [JsonProperty("userId")]
                public string UserId { get; set; } = string.Empty;

                [JsonProperty("vaild")]
                public bool Vaild { get; set; } = false;

                [JsonProperty("portName")]
                public string PortName { get; set; } = string.Empty;

                [JsonProperty("portType")]
                public int PortType { get; set; } = 0;

                [JsonProperty("deviceType")]
                public int DeviceType { get; set; } = 0;

                [JsonProperty("com")]
                public int? Com { get; set; } = 0;

                [JsonProperty("bandRate")]
                public int? BandRate { get; set; } = 0;

                [JsonProperty("parity")]
                public string Parity { get; set; } = string.Empty;

                [JsonProperty("dateBits")]
                public int? DateBits { get; set; } = 0;

                [JsonProperty("stopBit")]
                public int? StopBit { get; set; } = 0;

                [JsonProperty("respTimeOutMs")]
                public int RespTimeOutMs { get; set; } = 0;

                [JsonProperty("sampleIntervals")]
                public int SampleIntervals { get; set; } = 0;

                [JsonProperty("devConfigList")]
                public List<DevConfig> DevConfigList { get; set; } = new List<DevConfig>();
            }

            public class RootObject
            {
                [JsonProperty("id")]
                public string Id { get; set; } = string.Empty;

                [JsonProperty("userId")]
                public string UserId { get; set; } = string.Empty;

                [JsonProperty("groupPortId")]
                public string GroupPortId { get; set; } = string.Empty;

                [JsonProperty("name")]
                public string Name { get; set; } = string.Empty;

                [JsonProperty("type")]
                public int Type { get; set; } = 0;

                [JsonProperty("description")]
                public string Description { get; set; } = string.Empty;

                [JsonProperty("status")]
                public int Status { get; set; } = 0;

                [JsonProperty("createTime")]
                public string CreateTime { get; set; } = string.Empty;

                [JsonProperty("portConfigList")]
                public List<PortConfig> PortConfigList { get; set; } = new List<PortConfig>();
                public RootObject()
                {
                    // 添加一个无参数的构造函数
                }
            }

            public partial class MyPortList
            {
                [JsonProperty("code")]
                public string Code { get; set; } = string.Empty;

                [JsonProperty("msg")]
                public string Msg { get; set; } = string.Empty;

                [JsonProperty("data")]
                public RootObject data { get; set; } = new RootObject();

            }
        }


        public partial class MyDeviceList
        {
            public static MyDeviceList? FromJson(string json) => JsonConvert.DeserializeObject<MyDeviceList>(json, NSDevice.Converter.Settings);
        }

        public static class Serialize
        {
            public static string ToJson(this MyDeviceList self) => JsonConvert.SerializeObject(self, NSDevice.Converter.Settings);
        }

        internal static class Converter
        {
            public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                DateParseHandling = DateParseHandling.None,
                Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
            };
        }
    }

    namespace NSJsonUrl
    {
        public partial class MyConfigJsonUrls
        {
            [JsonProperty("code")]
            public string Code { get; set; } = string.Empty;

            [JsonProperty("msg")]
            public string Msg { get; set; } = string.Empty;

            [JsonProperty("data")]
            public List<Datum> Data { get; set; } = new List<Datum>();
        }

        public partial class Datum
        {
            [JsonProperty("md5")]
            public string Md5 { get; set; } = string.Empty;

            [JsonProperty("size")]
            public long Size { get; set; } = 0;

            [JsonProperty("url")]
            public string Url { get; set; } = string.Empty;
        }
    }

    class TransHttpManager
    {
        static TransHttpManager()
        {

        }

        private static readonly TransHttpManager instance = new TransHttpManager();
        public static NSProduct.MyProductList myProductList = new NSProduct.MyProductList();
        public static Dictionary<string, NSProduct.MyProduct> myDictProductList = new Dictionary<string, NSProduct.MyProduct>();
        public static Dictionary<string, NSDevice.MyDevice> myDictDeviceList = new Dictionary<string, NSDevice.MyDevice>();
        public static NSDevice.TransPortList.MyPortList myTransPortList = new NSDevice.TransPortList.MyPortList();
        public static Dictionary<string, NSDevice.TransPortList.PortConfig> myDictTransPortList = new Dictionary<string, NSDevice.TransPortList.PortConfig>();
        public static NSDevice.MyDeviceList myDeviceList = new NSDevice.MyDeviceList();
        public static NSJsonUrl.MyConfigJsonUrls myConfigJsonUrls = new NSJsonUrl.MyConfigJsonUrls();
        public string strDeviceInfoJson = "";
        public static TransHttpManager Instance
        {
            get
            {
                return instance;
            }
        }

        public void GetProductList(ref List<string> list)
        {
            string url = NetworkConfig.Instance.GetRemoteTransProductListUrl();
            RestResponse response = HttpManager.Get(url, NetworkConfig.Instance.GetRemoteTransToken());
            var rspData = RspTransWebsocketData.FromJson(response.Content ?? "");
            bool bRet = rspData?.IsValid() ?? false;
            if (response.StatusCode == System.Net.HttpStatusCode.OK && bRet)
            {
                LogManager.Debug("获取产品列表成功");
                myDictProductList.Clear();
                try
                {
                    var content = response.Content ?? "";
                    myProductList = JsonConvert.DeserializeObject<NSProduct.MyProductList>(content) ?? new NSProduct.MyProductList();   
                    foreach (var item in myProductList.data)
                    {
                        list.Add(item.name);
                        myDictProductList.Add(item.name, item);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error("json 解析出错" + ex.Message);
                }
            }
            else
            {
                LogManager.Error("获取产品列表失败"+response.ErrorMessage);
                LogManager.Error("获取产品列表失败内容" + response.Content);
            }
        }

        private string GetProductKey(string product)
        {
            string key = "";
            if (myDictProductList.ContainsKey(product))
            {
                key = myDictProductList[product].id;
            }
            return key;
        }

        public void GetDeviceList(ref List<string> list, string product)
        {
            string url = NetworkConfig.Instance.GetRemoteTransDeviceListUrl() + GetProductKey(product);
            RestResponse response = HttpManager.Get(url, NetworkConfig.Instance.GetRemoteTransToken());
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                list.Clear();
                LogManager.Debug("获取设备列表成功(" + product + ")");
                myDictDeviceList.Clear();
                try
                {
                    var content = response.Content ?? "";
                    myDeviceList = JsonConvert.DeserializeObject<NSDevice.MyDeviceList>(content) ?? new NSDevice.MyDeviceList();
                    strDeviceInfoJson = content;

                    foreach (var item in myDeviceList.data)
                    {
                        string json = JsonConvert.SerializeObject(item);
                        NSDevice.MyDevice device = JsonConvert.DeserializeObject<NSDevice.MyDevice>(json) ?? new NSDevice.MyDevice();
                        list.Add(device.name);
                        myDictDeviceList.Add(device.name, device);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error("json 解析出错" + ex.Message);
                }
            }
            else
            {
                LogManager.Error("获取设备列表失败(" + product + ")" + response.ErrorMessage);
            }
        }

        public void GetDeviceDetailList(ref List<NSDevice.MyDevice> list, string product)
        {
            string productKey = GetProductKey(product);
            foreach (var item in myDictDeviceList)
            {
                if (item.Value.productId == productKey)
                {
                    list.Add(item.Value);
                }
            }
        }

        public void GetTransPortList(ref List<string> list, string product)
        {
            string url = NetworkConfig.Instance.GetRemoteTransAllProductListUrl() + GetProductKey(product);
            RestResponse response = HttpManager.Get(url, NetworkConfig.Instance.GetRemoteTransToken());
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                list.Clear();
                myDictTransPortList.Clear();
                LogManager.Debug("获取透传端口列表成功(" + product + ")");
                try
                {
                    var content = response.Content ?? "";
                    myTransPortList = JsonConvert.DeserializeObject<NSDevice.TransPortList.MyPortList>(content) ?? new NSDevice.TransPortList.MyPortList();

                    foreach (var item in myTransPortList.data.PortConfigList)
                    {
                        list.Add(item.PortName);
                        myDictTransPortList.Add(item.PortName, item);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Error("json 解析出错" + ex.Message);
                }
            }
            else
            {
                LogManager.Error("获取透传端口列表失败(" + product + ")" + response.ErrorMessage);
            }
        }

        public bool GetPortType(string name)
        {
            bool type = false;
            if (myDictTransPortList.ContainsKey(name))
            {
                var item = myDictTransPortList[name];
                if(item.PortType == 1)// 1--串口  分--网口
                {
                    type = true;
                }
            }
            return type;
        }

        public string GetPortDeviceIdType(string name)
        {
            string deviceId = "";
            if (myDictTransPortList.ContainsKey(name))
            {
                var item = myDictTransPortList[name];
                deviceId = item.DeviceType.ToString();
            }
            return deviceId;
        }

        public string GetTargetPort(string name)
        {
            string target = "";
            if (myDictTransPortList.ContainsKey(name))
            {
                var item = myDictTransPortList[name];
                string comTemp = "COM" + item.Com.ToString();

                var serialPortSettings = new
                {
                    com = comTemp,
                    bandRate = item.BandRate.ToString(),
                    parity = item.Parity,
                    dateBits = item.DateBits.ToString(),
                    stopBit = item.StopBit.ToString()
                };

                target = JsonConvert.SerializeObject(serialPortSettings);
            }
            return target;
        }

        public string GetDeviceStatus(string device)
        {
            string status = "";
            if (myDictDeviceList.ContainsKey(device))
            {
                //status = myDictDeviceList[device].status;
            }
            return status;
        }

        public string GetDeviceId(string device)
        {
            string status = "";
            if (myDictDeviceList.ContainsKey(device))
            {
                status = myDictDeviceList[device].id;
            }
            return status;
        }

        public string GetDeviceClientId(string device)
        {
            string clientId = "";
            if (myDictDeviceList.ContainsKey(device))
            {
                clientId = myDictDeviceList[device].clientId;
            }
            return clientId;
        }

    }
}
